package com.xieyong.mywebsite.util;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xieyong.mywebsite.model.entity.User;
import com.xieyong.mywebsite.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.Map;

@Component
public class TokenUtil {

    private static UserService staticUserService;

    private static final String KEY_HMAC_SHA256 = "XIEYONG";

    @Autowired
    public void setUserService(UserService userServiceImpl) {
        TokenUtil.staticUserService = userServiceImpl;
    }

    public static String createToken(Map<String, Object> claims,String userName) {
        return JWT.create()
                .withClaim("claims", claims)   // 将用户信息保存到token里面作为载荷
                .withAudience(userName)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24)) // 添加过期时间,1天后token过期
//                .withExpiresAt(DateUtil.offsetDay(new Date(), 1))  // 1天后token过期
                .sign(Algorithm.HMAC256(KEY_HMAC_SHA256));     // 以password作为token的秘钥， HMAC256算法加密
    }

    public static Map<String, Object> parseToken(String token) {
//        获取当前用户的password
//        String password = TokenUtil.getUserByToken(token).getPassword();
//        不使用password来作为秘钥
        return JWT.require(Algorithm.HMAC256(KEY_HMAC_SHA256))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

    public static User getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        return TokenUtil.getUserByToken(token);
    }

    public static User getUserByToken(String token) {
//            拿到token的荷载中的aud数据并进行解析
        String userName = JWT.decode(token).getAudience().getFirst();
//            根据用户名去数据库查询数据
        return staticUserService.findByUserName(userName);
    }

}
